package com.hl.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hl.domain.Consultproblem;
import com.hl.mapper.ConsultproblemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ConsultproblemService {
    @Autowired
    private ConsultproblemMapper consultproblemMapper;

    //发表问题，插入数据
    public int addProblem(Consultproblem consultproblem){
        return consultproblemMapper.insert(consultproblem);
    }

    //联表查询问题表，用户表，同时返回总共有多少条回复
    public List<Consultproblem> selectAllAnd(Integer pageNo,Integer pageSize){
        //清除之前可能存在的分页参数
        PageHelper.clearPage();
        if (pageNo!=null&&pageSize!=null){
            PageHelper.startPage(pageNo,pageSize);
        }
        List<Consultproblem> consultproblems = consultproblemMapper.selectAllByPageAndUser();
        PageHelper.clearPage();
        //循环设置回复数量
        if (consultproblems!=null){
            for (Consultproblem consultproblem : consultproblems) {
                Long l = consultproblemMapper.selectAllreplys(consultproblem.getCid());
                consultproblem.setReplies(l);
            }
        };
        return consultproblems;
    }

    //模糊查询
    public Map<String,Consultproblem> selectAllByLike(String problemtitle , Integer pageNum, Integer pageSize,
    Date startTime, Date endTime){
        //清除之前可能存在的分页参数
        PageHelper.clearPage();
        if (pageNum!=null&&pageSize!=null){
            PageHelper.startPage(pageNum,pageSize);
        }
        List<Consultproblem> consultproblems = consultproblemMapper.selectAllByLike(problemtitle, startTime, endTime);
        PageHelper.clearPage();
        //循环设置回复数量
        if (consultproblems!=null){
            for (Consultproblem consultproblem : consultproblems) {
                Long l = consultproblemMapper.selectAllreplys(consultproblem.getCid());
                consultproblem.setReplies(l);
            }
        }
        PageInfo<Consultproblem> pageInfo = new PageInfo<>(consultproblems);
        Map map = new HashMap<>();
        map.put("list",consultproblems);
        map.put("total",pageInfo.getTotal());
        return map;
    }

    //根据id删除
    public int deleteByPrimaryKey(Long id){
        return consultproblemMapper.deleteByPrimaryKey(id);
    }

    //获取总条数分页
    public Map<String,Consultproblem> getTotalAndPage(Integer pageNo, Integer pageSize){//清除之前可能存在的分页参数
        List<Consultproblem> consultproblems = this.selectAllAnd(pageNo, pageSize);
        PageInfo<Consultproblem> pageInfo = new PageInfo<>(consultproblems);
        Map map = new HashMap<>();
        map.put("list",consultproblems);
        map.put("total",pageInfo.getTotal());
        return map;
    }
}
